﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using ST.Common.Data;
using ST.Common.Util;
using ST.Common.Util.Model;
using ST.Buz.Base;
using ST.Buz.Base.Entity;
using System;
using System.Collections.Generic;
using System.Linq;

namespace ST.Buz.Service
{
	public partial interface IServiceWXPayOrder
	{
		/// <summary>
		/// 获取信息
		/// </summary>
		/// <param name="id"></param>
		/// <exception cref="System.ArgumentNullException">参数有误时抛出</exception>
		/// <exception cref="ST.Common.Util.EntityNotFoundException">未找到要操作的记录时抛出</exception>
		/// <exception cref="ST.Common.Util.BuzException">其他错误时抛出</exception>
		/// <returns></returns>
		WX_PayOrder GetByOutTradeNo(string outTradeNo, bool deattached = false);
	}

	public partial class ServiceWXPayOrder
	{
		public ServiceWXPayOrder(BuzContext ctx,
			ILogger<ServiceWXPayOrder> log)
		{
			context = ctx;
			logger = log;
		}

		/// <summary>
		/// 获取信息
		/// </summary>
		/// <param name="id"></param>
		/// <exception cref="System.ArgumentNullException">参数有误时抛出</exception>
		/// <exception cref="ST.Common.Util.EntityNotFoundException">未找到要操作的记录时抛出</exception>
		/// <exception cref="ST.Common.Util.BuzException">其他错误时抛出</exception>
		/// <returns></returns>
		public WX_PayOrder GetByOutTradeNo(string outTradeNo, bool deattached = false)
		{
			try
			{
				if (string.IsNullOrEmpty(outTradeNo))
				{
					throw new ArgumentNullException("商户订单号");
				}
				var model = context.WXPayOrder.SingleOrDefault(m => m.OutTradeNO == outTradeNo);
				if (model == null)
				{
					throw new EntityNotFoundException("未找到商户订单号为" + outTradeNo + "的记录或记录已删除");
				}
				if (deattached)
				{
					var entity = context.Entry(model);
					entity.State = EntityState.Detached;
				}
				return model;
			}
			catch (ArgumentNullException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				throw ex;
			}
			catch (EntityNotFoundException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				throw ex;
			}
			catch (BuzException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				throw ex;
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				throw new BuzException(ex.Message, ex);
			}
		}
	}
}